package com.atguigu.srb.oss.controller.api;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;


@RestController
@RequestMapping("/api/oss/file")
@Slf4j
@Api(tags = "阿里云文件管理")
public class FileController {
    @Resource
    private FileService fileService;

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public R uploadFile(@ApiParam(value = "文件",required = true) @RequestParam("file") MultipartFile file,
                        @ApiParam(value = "模块",required = true) @RequestParam("module") String module){
        try {
            InputStream inputStream=file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream, module, originalFilename);
            return R.ok().message("文件上传成功").data("url",uploadUrl);
        }catch (Exception e){
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }

    @ApiOperation("删除OSS文件")
    @DeleteMapping("/remove")
    public R deleteFile(@ApiParam(value = "要删除的文件路径", required = true) @RequestParam("fileUrl") String fileUrl){
       fileService.removeFile(fileUrl);
       return R.ok().message("文件删除成功");
    }
}
